<template>
  <el-dialog
    top="30px"
    width="80%"
    title="签约登记"
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <div id="print-wrap">
      <table class="table table-bordered vertical-align-middle text-center" v-loading="loading">
        <tbody>
          <tr>
            <td>主体姓名</td>
            <td>{{ relatedData.customer_name || '' }}</td>
            <td>贷款金额（万元）</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <span v-if="isViewMode">{{ params.reply_funds }}</span>
              <input
                type="number"
                class="form-control"
                placeholder="请输入贷款金额"
                v-model="params.reply_funds"
                v-else
              />
            </td>
            <td>用款期限（年）</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <span v-if="isViewMode" class="px-2">{{ params.warranty_period || '-' }}</span>
              <el-input-number
                v-model="params.warranty_period"
                v-else
                style="width: 70%"
                :controls="false"
                :min="0"
              ></el-input-number>
              年
            </td>
          </tr>
          <tr>
            <td>贷款利率</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <span v-if="isViewMode" class="px-2">{{ params.load_rate || '-' }}</span>
              <el-input-number
                v-model="params.load_rate"
                v-else
                style="width: 70%"
                :controls="false"
                :min="0"
              ></el-input-number>
              %
            </td>
            <td>贷款时间</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <span v-if="isViewMode" class="px-2">
                {{ $utils.dateFormat(params.load_date, 'yyyy.MM.dd') }}
              </span>
              <el-date-picker
                v-model="params.load_date"
                v-else
                placeholder="项目贷款时间"
                class="w-100"
                type="date"
                value-format="yyyy-MM-dd"
                :clearable="true"
              ></el-date-picker>
            </td>
            <td>到期时间</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <span v-if="isViewMode" class="px-2">
                {{ $utils.dateFormat(params.load_end_date, 'yyyy.MM.dd') }}
              </span>
              <el-date-picker
                v-model="params.load_end_date"
                v-else
                placeholder="项目到期时间"
                class="w-100"
                type="date"
                value-format="yyyy-MM-dd"
                :clearable="true"
              ></el-date-picker>
            </td>
          </tr>

          <tr>
            <td>担保主审</td>
            <td
              :class="
                isViewMode || (!isMission && +relatedData.submit_type === 1)
                  ? ''
                  : 'report-input-td'
              "
            >
              <span v-if="isViewMode || (!isMission && +relatedData.submit_type === 1)">
                {{ params.project_chief }}
              </span>
              <select-staff
                v-else
                class="w-100"
                @change="handleStaffChange"
                v-model="params.project_chief"
              ></select-staff>
            </td>
            <td>主审意见</td>
            <td
              colspan="3"
              :class="
                isViewMode || (!isMission && +relatedData.submit_type === 1)
                  ? ''
                  : 'report-input-td'
              "
            >
              <span v-if="isViewMode || (!isMission && +relatedData.submit_type === 1)">
                {{ params.approval_option || '-' }}
              </span>
              <input
                type="text"
                class="form-control"
                placeholder="请输入意见（非必填）"
                v-model="params.approval_option"
                v-else
              />
            </td>
          </tr>
          <tr>
            <td>银行经理</td>
            <td :class="isViewMode || !isBankOrg ? '' : 'report-input-td'">
              <span v-if="isViewMode || !isBankOrg">{{ params.bank_concat_name }}</span>
              <select-staff
                v-else
                class="w-100"
                @change="handleStaffBankChange"
                v-model="params.bank_concat"
              ></select-staff>
            </td>
            <td>经理意见</td>
            <td colspan="3" :class="isViewMode || !isBankOrg ? '' : 'report-input-td'">
              <span v-if="isViewMode || !isBankOrg">{{ params.bank_concat_option || '-' }}</span>
              <input
                type="text"
                class="form-control"
                placeholder="请输入经理意见（非必填）"
                v-model="params.bank_concat_option"
                v-else
              />
            </td>
          </tr>

          <tr v-if="isBankOrg || isViewMode">
            <td>借款合同编号</td>
            <td colspan="2" :class="isViewMode ? '' : 'report-input-td'">
              <input
                type="text"
                class="form-control"
                placeholder="请输入借款合同编号"
                v-model="params.load_contract"
                v-if="!isViewMode"
              />
              <span v-else>{{ params.load_contract || '-' }}</span>
            </td>
            <td>保证保合同编号</td>
            <td colspan="2" :class="isViewMode ? '' : 'report-input-td'">
              <input
                type="text"
                class="form-control"
                placeholder="请输入保证保合同编号"
                v-model="params.gua_contract"
                v-if="!isViewMode"
              />
              <span v-else>{{ params.gua_contract || '-' }}</span>
            </td>
          </tr>

          <tr v-if="isCreditOrg || isViewMode">
            <td>委托合同编号</td>
            <td colspan="2" :class="isViewMode ? '' : 'report-input-td'">
              <input
                type="text"
                class="form-control"
                placeholder="请输入委托合同编号"
                v-model="params.com_contract"
                v-if="!isViewMode"
              />
              <span v-else>{{ params.com_contract || '-' }}</span>
            </td>
            <td>反担保合同编号</td>
            <td colspan="2" :class="isViewMode ? '' : 'report-input-td'">
              <input
                type="text"
                class="form-control"
                placeholder="请输入反担保合同编号"
                v-model="params.warranty_contract"
                v-if="!isViewMode"
              />
              <span v-else>{{ params.warranty_contract || '-' }}</span>
            </td>
          </tr>

          <tr v-if="isCreditOrg || isViewMode">
            <td>担保意向函编号</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <input
                type="text"
                class="form-control"
                placeholder="请输入担保意向函编号"
                v-model="params.letter_intent"
                v-if="!isViewMode"
              />
              <span v-else>{{ params.letter_intent || '-' }}</span>
            </td>
            <td>放款通知书编号</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <input
                type="text"
                class="form-control"
                placeholder="请输入放款通知书编号"
                v-model="params.loan_notice"
                v-if="!isViewMode"
              />
              <span v-else>{{ params.loan_notice || '-' }}</span>
            </td>
            <td>联保反担保承诺书</td>
            <td :class="isViewMode ? '' : 'report-input-td'">
              <input
                type="text"
                class="form-control"
                placeholder="请输入联保反担保承诺书"
                v-model="params.reply_no"
                v-if="!isViewMode"
              />
              <span v-else>{{ params.reply_no || '-' }}</span>
            </td>
          </tr>

          <tr>
            <td>银行名称</td>
            <td>{{ relatedData.bank_name }}</td>
            <td>还款付息方式</td>
            <td colspan="3">
              <div v-if="isViewMode" class="row">
                <div class="col d-flex align-items-center">
                  <span>{{ enumRepayType[params.repay_type] || '-' }}</span>
                </div>
                <div class="col">
                  <el-button @click="showViewRepayList">查看还款计划</el-button>
                </div>
              </div>
              <div class="row" v-else>
                <div class="col d-flex align-items-center">
                  <el-radio-group v-model="repayType" @change="onRepayTypeChange">
                    <el-radio v-for="(value, key) in enumRepayType" :label="key" :key="key">
                      {{ value }}
                    </el-radio>
                  </el-radio-group>
                </div>
                <div class="col">
                  <el-button @click="showRepayList">生成还款计划</el-button>
                </div>
              </div>
            </td>
          </tr>

          <tr>
            <td>附件</td>
            <td colspan="5" class="text-left">
              <div>
                <upload-oss
                  multiple
                  accept="image/*"
                  listType="picture-card"
                  :limit="10"
                  :file-list="attachFileList"
                  :on-complete="handleImagesComplete"
                  v-if="!isViewMode"
                  ref="attachOss"
                ></upload-oss>
                <img-card v-else :images="attachImages"></img-card>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="text-center" v-if="!isViewMode">
      <el-button class="btn-long" type="primary" @click="handlePass">登记</el-button>
      <el-button class="btn-long" type="danger" @click="handleDismiss">取消</el-button>
    </div>

    <el-dialog
      top="30px"
      width="600px"
      append-to-body
      title="还款计划"
      class="dialog-sm"
      :close-on-click-modal="false"
      :before-close="onRepayClose"
      :visible.sync="repayVisible"
    >
      <el-table :data="viewRepayList" :height="dialogMaxheight" border v-if="repayListExist">
        <el-table-column label="还款时间" prop="pay_time" align="center"></el-table-column>
        <el-table-column label="是否还息" align="center">
          <template slot-scope="scope">
            <span>{{ enumRepayInterest[scope.row.is_interest] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="本金（万元）" prop="capital" align="center"></el-table-column>
      </el-table>

      <div v-else>
        <el-table :data="repayList" :height="dialogMaxheight" border cell-class-name="input-td">
          <el-table-column label="还款时间">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.pay_time"
                type="date"
                class="w-100 text-center"
                value-format="yyyy-MM-dd"
                format="yyyy年MM月dd日"
                :clearable="false"
                :placeholder="`选择${scope.$index === 0 ? '开始' : ''}还款时间`"
                @change="v => onSelectFirstRepayDate(v, scope.$index)"
              ></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="是否还息">
            <template slot-scope="scope">
              <div v-if="isLastMonthAtQuarter(scope.row.pay_time)">
                <c-select v-model="scope.row.is_interest" :options="enumRepayInterest"></c-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="本金（万元）">
            <template slot-scope="scope">
              <div class="d-flex">
                <el-input
                  v-model="scope.row.capital"
                  type="number"
                  class="flex-1"
                  placeholder="输入本金"
                ></el-input>
                <div
                  class="auto-fill-icon"
                  title="自动填写到所有下面的列"
                  @click="onAutoFill(scope.row, scope.$index)"
                >
                  <i class="fa fa-fw fa-level-down"></i>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="row mt-3" v-show="!repayListExist">
          <div class="col text-center">
            <el-button class="btn-long" @click="onRepayListDismiss">取消</el-button>
          </div>
          <div class="col text-center">
            <el-button class="btn-long" type="primary" @click="onRepayListFinsish">完成</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import SelectStaff from '@/components/select/SelectStaff'
import ImgCard from '@/components/ImgCard'
import { enumRepayType } from '@/credit/plugins/enum'
import { arrayFromString } from '@vimi/utils-tool'

export default {
  components: {
    SelectStaff,
    ImgCard,
  },
  props: {
    visible: Boolean,
    viewMode: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      loading: false,
      tableName: 'credit_level_review',
      tableRow: {},
      params: {
        reply_funds: 0, // 贷款金额
        repay_type: '', // 还款付息方式
        warranty_period: '', // 贷款期限
        load_rate: '', // 贷款利率
        load_date: '', // 贷款时间
        load_end_date: '', // 到期时间
        project_chief: '', // 项目经理
        approval_person: '', // 项目经理id
        approval_option: '', // 项目经理意见
        bank_concat_name: '', // 银行经理名字
        bank_concat: '', // 银行经理id
        bank_concat_option: '', // 银行经理意见
        load_contract: '', // 借款合同编号
        gua_contract: '', // 保证保合同编号
        com_contract: '', // 委托合同编号
        warranty_contract: '', // 反担保合同编号
        letter_intent: '', // 担保意向函编号
        loan_notice: '', // 放款通知书编号
        reply_no: '', // 联保反担保承诺书
      },
      projectChief: '',
      attachFileList: [],
      isReviewApiError: true,

      // 还款计划
      viewRepayList: [],
      viewRepayListError: true,
      repayType: '',
      enumRepayType,
      enumRepayInterest: {
        0: '否',
        1: '是',
      },
      repayList: [],
      repayVisible: false,
      repayLoading: false,
      dialogMaxheight: 500,
    }
  },
  computed: {
    ...mapGetters(['org', 'user']),
    isViewMode() {
      return this.viewMode
    },
    // || +this.relatedData.approval_register_status !== 0
    isBankOrg() {
      return this.org.orgClass === 'org_bank'
    },
    isMission() {
      return +this.user.orgRegionLever === 3
    },
    isCreditOrg() {
      return !this.isBankOrg
    },
    attachImages() {
      return this.attachFileList.map(item => item.url)
    },
    relatedId() {
      return this.relatedData.customer_related_id
    },
    repayListExist() {
      return this.isViewMode
    },
    repayMonthType() {
      return +this.params.repay_type === 1
    },
  },
  watch: {
    relatedData: {
      handler: 'getData',
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async getData() {
      if (!this.relatedId) {
        Object.keys(this.params).forEach(key => {
          this.params[key] = ''
        })
        this.tableRow = {}
        return
      }

      this.loading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, {
          'customer_related_id.eq': this.relatedId,
        })
      )
      this.loading = false

      if (err) {
        this.isReviewApiError = true
        return
      } else {
        this.isReviewApiError = false
      }
      this.tableRow = (res && res.data && res.data.length && res.data[0]) || {}
      Object.keys(this.params).forEach(key => {
        this.params[key] = this.tableRow[key] || ''
      })
      if (!this.params.approval_person) {
        this.params.approval_person = this.relatedData.res_a || ''
        this.params.project_chief = this.relatedData.res_a_name || ''
      }
      this.params.customer_related_id = this.relatedId
      this.params.is_approval = '1'
      this.attachFileList = arrayFromString(this.tableRow.attachment).map(img => {
        return { name: '', url: img }
      })
      if (!this.params.reply_funds) {
        this.params.reply_funds = this.relatedData.apply_funds
      }
      this.repayType = this.params.repay_type
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleStaffChange(v, n) {
      this.params.project_chief = n
    },
    handleStaffBankChange(v, n) {
      this.params.bank_concat_name = n
    },
    handlePass() {
      if (this.isReviewApiError) {
        return this.$message.error('获取登记信息失败，请刷新重试！')
      }

      if (this.isBankOrg) {
        if (!this.validatorBank()) {
          return
        }
      } else {
        if (!this.validatorCredit()) {
          return
        }
      }

      this.$refs.attachOss.submit()
    },
    handleDismiss() {
      this.$emit('update:visible', false)
    },
    validatorBank() {
      const enumValid = {
        repay_type: '请选择还款付息方式',
        load_date: '请输入贷款时间',
        load_end_date: '请输入到期时间',
        // project_chief: '请输入项目经理',
        // approval_option: '请输入项目经理意见',
        load_contract: '请输入借款合同编号',
        gua_contract: '请输入保证保合同编号',
        // com_contract: '请输入委托合同编号',
        // warranty_contract: '请输入反担保合同编号',
        // letter_intent: '请输入担保意向函编号',
        // loan_notice: '请输入放款通知书编号'
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.params[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },
    validatorCredit() {
      const enumValid = {
        load_date: '请输入贷款时间',
        load_end_date: '请输入到期时间',
        project_chief: '请输入项目经理',
        // approval_option: '请输入项目经理意见',
        // load_contract: '请输入借款合同编号',
        // gua_contract: '请输入保证保合同编号',
        com_contract: '请输入委托合同编号',
        warranty_contract: '请输入反担保合同编号',
        letter_intent: '请输入担保意向函编号',
        loan_notice: '请输入放款通知书编号',
      }

      const keys = Object.keys(enumValid)
      for (const key of keys) {
        if (!this.params[key]) {
          this.$message.error(enumValid[key])
          return false
        }
      }

      return true
    },

    handleImagesComplete(images = []) {
      const imageStr = images.length ? `["${images.map(item => item.url).join('","')}"]` : ''
      this.onSave(imageStr)
    },

    onSave(imageStr = '') {
      const data = [{ ...this.params }]
      data[0].attachment = imageStr
      data[0].customer_related_id = this.relatedData.customer_related_id
      if (this.tableRow.id) {
        data[0].id = this.tableRow.id
      }
      this.$utils
        .msgbox({
          message: `确定登记?`,
          type: 'info',
          beforeClose: () => this.$api.updateBatch(this.$serviceName, this.tableName, data),
        })
        .then(() => {
          this.$message.success('登记成功！')
          this.$emit('success', true)
          this.$store.dispatch('getTaskCountTown')
          if (this.isBankOrg) {
            this.addRepayList()
          } else {
            this.$emit('success', false)
            this.beforeClose()
          }
        })
        .catch(() => this.$message.error(`登记失败，请重试！`))
    },

    // 还款计划
    initDialogMaxHeight() {
      const clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight
      this.dialogMaxheight = clientHeight - 300
    },
    showViewRepayList() {
      this.repayVisible = true
      if (!this.viewRepayList.length) {
        this.getRepayList()
      }
    },
    async getRepayList() {
      this.repayLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData(
          this.$serviceName,
          'datum_repay_list',
          {
            'customer_related_id.eq': this.relatedId,
          },
          { pay_time: 'asc' }
        )
      )
      this.repayLoading = false
      this.viewRepayList = ((res && res.data) || []).map(item => {
        item.pay_time = this.$utils.dateFormat(item.pay_time, 'yyyy年MM月dd日')
        return item
      })
      this.viewRepayListError = Boolean(err)
    },
    async addRepayList() {
      if (this.repayListExist) {
        return
      }
      const repayListData = []
      for (const item of this.repayList) {
        if (item.pay_time) {
          repayListData.push({
            customer_related_id: this.relatedId,
            pay_time: item.pay_time,
            is_interest: item.is_interest,
            capital: item.capital,
          })
        }
      }
      if (!repayListData.length) {
        return
      }
      const [, err] = await this.$utils.promise(
        this.$api.addBatch(this.$serviceName, 'datum_repay_list', repayListData)
      )
      if (err) {
        return this.$message.error('生成还款计划失败，请重试')
      }
      this.$emit('success', false)
      this.beforeClose()
      this.getRepayList()
    },
    showRepayList() {
      if (this.repayList.length > 1) {
        // 之前修改的
        this.repayVisible = true
        return
      }
      if (!this.params.repay_type) {
        return this.$message.warning('请先选择还款设置')
      }
      // 不是按照贷款日期来计划开始时间
      // const startDate = this.repayStart ? new Date(this.repayStart) : ''
      // if (!startDate) {
      //   return this.$message.warning('请先填写贷款日期')
      // }
      const period = +this.params.warranty_period || 0
      if (!period) {
        return this.$message.warning('没有用款期限')
      }
      this.initRepayList()
      this.repayVisible = true
    },
    onSelectFirstRepayDate(val, index) {
      if (!val || index > 0) {
        return
      }
      this.repayList = [{ ...this.repayList[0] }]
      const startDate = new Date(val)
      const startYear = startDate.getFullYear()
      const startMonth = startDate.getMonth() + 1
      const startDay = startDate.getDate()
      const period = +this.params.warranty_period || 0
      for (let i = 1; i < period * 12; i++) {
        let tempMonth = (startMonth + i) % 12
        if (tempMonth === 0) {
          tempMonth = 12
        }
        const tempYear =
          startYear + (Math.floor((startMonth + i) / 12) - (tempMonth === 12 ? 1 : 0))
        this.repayList.push({
          pay_time: `${tempYear}-${this.autoFillZero(tempMonth)}-${this.autoFillZero(startDay)}`,
          capital: '',
          is_interest: this.repayMonthType ? '1' : tempMonth % 3 === 0 ? '1' : '0',
          canChange: this.repayMonthType ? true : tempMonth % 3 === 0,
        })
      }
    },
    onRepayClose() {
      this.repayVisible = false
    },
    onRepayTypeChange(val) {
      if (this.repayList.length < 2) {
        this.params.repay_type = val
        return
      }
      this.repayType = this.params.repay_type
      this.$confirm('已经有还款计划，更换还款设置后需要重新生成，确定修改？', '提示', {
        confirmButtonText: '确定修改',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.initRepayList()
          this.repayType = val
          this.params.repay_type = val
        })
        .catch(() => {})
    },
    autoFillZero(num) {
      return num > 9 ? num : `0${num}`
    },
    initRepayList() {
      this.repayList = [
        {
          pay_time: '',
          is_interest: '1',
          capital: '',
        },
      ]
    },
    onRepayListDismiss() {
      if (this.repayList.length < 2) {
        this.onRepayClose()
      } else {
        this.$confirm('确定取消还款计划，并重置填写的数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.initRepayList()
            this.onRepayClose()
          })
          .catch(() => {})
      }
    },
    onRepayListFinsish() {
      this.repayVisible = false
    },
    onAutoFill(row, index) {
      for (let i = index; i < this.repayList.length; i++) {
        this.repayList[i].capital = row.capital
      }
    },
    isLastMonthAtQuarter(payTime) {
      if (this.repayMonthType || !payTime) {
        return true
      }
      return (new Date(payTime).getMonth() + 1) % 3 === 0
    },
  },
}
</script>

<style lang="scss" scoped>
.vertical-align-middle td {
  vertical-align: middle;
}
.bg-gray {
  background-color: $gray-200;
}
.report-input-td {
  background-color: #ffe;
}
</style>
